package interpreter.bytecodes;

import interpreter.VirtualMachine;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 *
 * @author Kristofer Selbekk
 */
public class ReturnByteCode extends ByteCode {

    private String id; // May or may not be used
    private int address;
    private int returnedValue;

    /**
     * Initializes the byte code with no arguments
     */
    public void init( Vector<String> args ) {
        try {
            id = args.get(0);
        } catch( NumberFormatException nfe ) {
            // If bad format
            System.out.println("Bad format!");
            System.exit(-1);
        } catch( ArrayIndexOutOfBoundsException aioob ) {
            // Do nothing, it's allowed to have no argument
            id = null;
        } catch( NoSuchElementException nse ) {
            // If empty argument
            System.out.println("Empty vector! But this might be ok");
            System.exit(-1);
        } catch( NullPointerException npe ) {
            // If argument missing
            System.out.println("Argument given = null.");
            System.exit(-1);
        }
    }

    /**
     * Action: Returns to right after where the function was called
     *
     * @param rt the Virtual Machine reference
     */
    public void exec( VirtualMachine rt ) {

        returnedValue = rt.getTopOfStack();
        rt.popTopFrame();
        
        rt.setPC( rt.popReturnAddress() + 1 ); // You want to return to the next statement after the function call
    }

    public Object getArgs() {
        return id;
    }

    public void setAddress( int addr ) {
        address = addr;
    }
    public int getAddress() {
        return address;
    }

    public String toString() {
        StringTokenizer token;
        String baseID = "";
        if( id != null ) {
            token = new StringTokenizer(id, "<");
            baseID = token.nextToken();
        }

        return super.toString() + "\texit " + baseID+": "+ returnedValue;
    }
}